package com.kidback.bbloc259.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewbinding.ViewBinding;

import com.kidback.bbloc259.util.CollectionUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;

/**
 * Created by meikai on 2020/06/02.
 */
public abstract class BaseActivity<T extends ViewBinding> extends AppCompatActivity {

    public AppCompatActivity activity;
    public List<Disposable> disposableList = new ArrayList<>();

    public T viewBinding;
    public LayoutInflater inflater;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        activity = this;

        beforeOnCreate();

        super.onCreate(savedInstanceState);

        inflater = LayoutInflater.from(this);
        viewBinding = getViewBinding();
        if (viewBinding != null) {
            setContentView(viewBinding.getRoot());
        }

        //界面构建完成后才接收事件，防止某些粘性事件操作未初始化的view
        EventBus.getDefault().register(this);
    }

    @Override
    public void setContentView(View view) {
        super.setContentView(view);
        initView();
        loadData();
    }

    public abstract T getViewBinding();

    protected void beforeOnCreate() {

    }

    protected abstract void initView();

    protected abstract void loadData();

    protected View.OnClickListener onBackClickListener = v -> finish();

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        disposeAll();
        EventBus.getDefault().unregister(this);
    }

    protected void disposeAll() {
        for (int i = 0; i < CollectionUtils.size(disposableList); i++) {
            Disposable disposable = CollectionUtils.get(disposableList, i);
            if (disposable != null && !disposable.isDisposed()) {
                disposable.dispose();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNoneEvent(Object object) {
    }

}
